package cn.wolfcode.crm.shiro.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IRoleService;

public class CRMRealm extends AuthorizingRealm {
	@Autowired
	private IEmployeeService employeeService;

	@Autowired
	private IRoleService roleService;

	@Override
	public boolean isPermitted(PrincipalCollection principals, String permission) {
		Employee employee = (Employee) principals.getPrimaryPrincipal();
		return employee.isAdmin() || super.isPermitted(principals, permission);
	}

	@Override
	public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
		Employee employee = (Employee) principals.getPrimaryPrincipal();
		return employee.isAdmin() || super.hasRole(principals, roleIdentifier);
	}

	/**
	 * 执行授权逻辑
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("执行授权逻辑");

		// 给资源进行授权
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		// 添加资源的授权字符串
		// info.addStringPermission("user:add");

		// 到数据库查询当前登录用户的授权字符串
		// 获取当前登录用户
		Subject subject = SecurityUtils.getSubject();
		Employee employee = (Employee) subject.getPrincipal();
		Employee dbEmployee = employeeService.selectById(employee.getId());

		List<Role> roles = employee.getRoles();
		for (Role role : roles) {
			System.out.println(role.getSn());
			info.addRole(role.getSn());

			role = roleService.get(role.getId());
			List<Permission> permissions = role.getPermissions();
			for (Permission permission : permissions) {
				System.out.println(permission.getExpression());
				info.addStringPermission(permission.getExpression());
			}

		}

		return info;
	}

	/**
	 * 执行认证逻辑
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		System.out.println("执行认证逻辑");

		// 编写shiro判断逻辑，判断用户名和密码
		// 1.判断用户名
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;

		Employee employee = employeeService.selectByEmail(token.getUsername());

		if (employee == null) {
			// 用户名不存在
			return null;// shiro底层会抛出UnKnowAccountException
		}

		// 2.判断密码
		return new SimpleAuthenticationInfo(employee, employee.getPassword(), employee.getEmail());
	}

}
